﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Showroom.BLL;
using MyGeneration.dOOdads;
using System.IO;
using System.Drawing;
using System.Drawing.Drawing2D;
using ShowroomBLL.BLL;

namespace ShowroomMobile
{
    public partial class UpdateProduct : AdminBasePage
    {
        private int ProductID
        {
            get
            {
                return string.IsNullOrEmpty(Request["id"]) ? 0 : Convert.ToInt32(Request["id"]);
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ((AdminSite)Page.Master).SetTitlePage((ProductID == 0) ? "Add Product" : "Edit Product");
                
                View_CategoryTree categoryTree = new View_CategoryTree();
                categoryTree.LoadAll();
                categoryTree.Sort = View_CategoryTree.ColumnNames.Path + " asc";
                Utilities.LoadListBox(lstCategory, categoryTree.DefaultView, View_CategoryTree.ColumnNames.Path, View_CategoryTree.ColumnNames.ID, false);
                if (!string.IsNullOrEmpty(Request.QueryString["CateID"]))
                {
                    for (int i = 0; i < lstCategory.Items.Count; i++)
                    {
                        if (lstCategory.Items[i].Value == Request.QueryString["CateID"])
                        {
                            lstCategory.Items[i].Selected = true;
                            break;
                        }
                    }
                }

                if (ProductID > 0)
                {
                    //Load edit data
                    Showroom.BLL.Products prod = Showroom.BLL.Products.GetByID(ProductID);
                    if (prod.RowCount > 0)
                    {
                        txtProductName.Text = prod.s_Name;
                        ftbDescription.Text = prod.s_Description;
                        txtPrice.Text = (string.IsNullOrEmpty(prod.s_Price) ? "0.00" : prod.s_Price);

                        CategoryProduct prodCate = new CategoryProduct();
                        prodCate.Where.ProductID.Value = ProductID;
                        prodCate.Query.Load();

                        if (prodCate.RowCount > 0)
                        {
                            for (int i = 0; i < lstCategory.Items.Count; i++)
                            {
                                prodCate.Filter = CategoryProduct.ColumnNames.CategoryID + " = " + lstCategory.Items[i].Value;
                                if (prodCate.RowCount > 0)
                                    lstCategory.Items[i].Selected = true;
                            }
                        }

                        //Load image data
                        LoadProductImages();
                    }
                    else
                    {

                    }
                }
            }
        }

        protected void btnCancel_OnClick(object sender, EventArgs e)
        {
            Response.Redirect("~/ManagerProducts.aspx");
        }

        protected void btnSave_OnClick(object sender, EventArgs e)
        {
            TransactionMgr tx = TransactionMgr.ThreadTransactionMgr();
            try
            {
                try
                {
                    if(!Utilities.isMoneyNumber(txtPrice.Text.Trim()))
                    {
                        ScriptManager.RegisterStartupScript(this, typeof(Page), Guid.NewGuid().ToString(), String.Format("showErrorAlert('Star Case', 'Price must be a number!', 8000);", 1), true);
                        txtPrice.Focus();
                        return;
                    }
                    tx.BeginTransaction();

                    Showroom.BLL.Products prod = new Showroom.BLL.Products();
                    if (ProductID > 0)
                    {
                        prod = Showroom.BLL.Products.GetByID(ProductID);

                        CategoryProduct prodCate = new CategoryProduct();
                        prodCate.Where.ProductID.Value = ProductID;
                        prodCate.Query.Load();
                        prodCate.DeleteAll();

                        for (int i = 0; i < lstCategory.Items.Count; i++)
                        {
                            if (lstCategory.Items[i].Selected)
                            {
                                prodCate.AddNew();
                                prodCate.ProductID = ProductID;
                                prodCate.s_CategoryID = lstCategory.Items[i].Value;
                            }
                        }

                        prodCate.Save();
                    }
                    else
                    {
                        prod.AddNew();
                    }

                    prod.Name = txtProductName.Text.Trim();
                    prod.Description = ftbDescription.Text;
                    prod.Price = Convert.ToDecimal(txtPrice.Text.Replace("$", ""));
                    prod.Save();

                    #region ==UPLOAD IMAGES==
                    string[] validExt = { "jpg", "png", "bmp", "gif" };
                    #endregion
                    string filename = string.Empty;

                    // Get the HttpFileCollection
                    HttpFileCollection hfc = Request.Files;
                    //Check File Type
                    for (int i = 0; i < hfc.Count; i++)
                    {
                        HttpPostedFile hpf = hfc[i];
                        if (hpf.ContentLength > 0)
                        {
                            if (!validExt.Contains<string>(Path.GetExtension(hpf.FileName).ToLower().Replace(".", "")))
                            {
                                tx.RollbackTransaction();
                                ScriptManager.RegisterStartupScript(this, typeof(Page), Guid.NewGuid().ToString(), String.Format("showErrorAlert('Star Case', 'Invalid image!', 8000);", 1), true);
                                return;
                            }
                        }
                    }
                    //Save Image Files
                    string pathOriginal = Server.MapPath("~") + "\\" + Utilities.GetKeySetting("PathUploadImageOriginal");
                    string pathThumb = Server.MapPath("~") + "\\" + Utilities.GetKeySetting("PathUploadImageThumb");
                    string pathMobile = Server.MapPath("~") + "\\" + Utilities.GetKeySetting("PathUploadImageMobile");
                    int widthThumb = Convert.ToInt32(Utilities.GetKeySetting("WidthThumb"));
                    int widthMobile = Convert.ToInt32(Utilities.GetKeySetting("WidthMobile"));
                    DirectoryInfo dInfo = new DirectoryInfo(pathOriginal);
                    if (!dInfo.Exists)
                        dInfo.Create();
                    dInfo = new DirectoryInfo(pathThumb);
                    if (!dInfo.Exists)
                        dInfo.Create();
                    dInfo = new DirectoryInfo(pathMobile);
                    if (!dInfo.Exists)
                        dInfo.Create();
                    bool isDefault = (rptImages.Items == null || rptImages.Items.Count == 0);
                    if (hfc.Count > 0)
                    {
                        ProductImages prodImages = new ProductImages();
                        for (int i = 0; i < hfc.Count; i++)
                        {
                            HttpPostedFile hpf = hfc[i];
                            if (hpf.ContentLength > 0)
                            {
                                prodImages.AddNew();
                                filename = Guid.NewGuid().ToString() + Path.GetExtension(hpf.FileName).ToLower();
                                //Save Original File
                                hpf.SaveAs(pathOriginal + "\\" +
                                  System.IO.Path.GetFileName(filename));
                                //Save Thumb File
                                this.SaveImage(hpf, pathThumb + "\\" + System.IO.Path.GetFileName(filename), widthThumb);
                                //Save Mobile File
                                this.SaveImage(hpf, pathMobile + "\\" + System.IO.Path.GetFileName(filename), widthMobile);
                                prodImages.s_OriginalUrl = filename;
                                prodImages.s_ProductID = prod.s_ID;
                                prodImages.Default = isDefault;
                                isDefault = false;
                            }
                        }
                        prodImages.Save();
                    }
                    else
                    {
                        if (isDefault)
                        {
                            tx.RollbackTransaction();
                            ScriptManager.RegisterStartupScript(this, typeof(Page), Guid.NewGuid().ToString(), String.Format("showErrorAlert('Star Case', 'Please select an image file!', 8000);", 1), true);
                            return;
                        }
                    }

                    //Delete Deleted Image
                    string listID = hidDeleteImageID.Value;
                    if (!string.IsNullOrEmpty(listID))
                    {
                        listID = listID.Trim(',');
                        ProductImages.DeleteImagesByListID(listID);
                    }

                    string defaultImageID = hidImageDefaultID.Value;
                    if (!string.IsNullOrEmpty(defaultImageID))
                    {
                        ProductImages.SetDefaultImage(ProductID, Convert.ToInt32(defaultImageID));
                    }

                    tx.CommitTransaction();
                    ScriptManager.RegisterStartupScript(this, typeof(Page), Guid.NewGuid().ToString(), String.Format("showNotification('Star Case', 'Save successfully!', 8000);", 1), true);
                    if(string.IsNullOrEmpty(Request.QueryString["ReturnURL"]))
                        Response.Redirect("~/ManagerProducts.aspx");
                    else
                        Response.Redirect(Request.QueryString["ReturnURL"]);
                }
                catch (Exception ex)
                {
                    tx.RollbackTransaction();
                    ErrorLog.WriteToFile("ManagerProducts.aspx.cs", "btnSave_OnClick", ex.StackTrace);
                }
            }
            catch (Exception ex)
            {
                ErrorLog.WriteToFile("UpdateProduct.aspx.cs", "btnSave_OnClick", ex.StackTrace);
                ScriptManager.RegisterStartupScript(this, typeof(Page), Guid.NewGuid().ToString(), String.Format("showErrorAlert('Star Case', '{0}', 8000);", ex.Message), true);
            }
        }

        protected void rptImages_ItemCommand(object source, RepeaterCommandEventArgs e)
        {

        }

        private void LoadProductImages()
        {
            ProductImages imgs = ProductImages.GetByProductID(ProductID);

            imgs.Filter = ProductImages.ColumnNames.Default + " = 1";
            if (imgs.RowCount > 0)
            {
                hidImageDefaultID.Value = imgs.s_ID;
            }

            imgs.Rewind();
            imgs.Filter = string.Empty;
            rptImages.DataSource = imgs.DefaultView;
            rptImages.DataBind();
        }

        private void SaveImage(HttpPostedFile file, string saveAs, int maxWidth)
        {
            try
            {
                int width = 0, height = 0;
                Bitmap originalBMP = new Bitmap(file.InputStream);

                double dblCoef = originalBMP.Height / (double)originalBMP.Width;
                width = maxWidth;
                height = Convert.ToInt32(dblCoef * maxWidth);

                Bitmap newBMP = new Bitmap(originalBMP, width, height);

                //Create a graphic based on the new bitmap
                Graphics oGraphics = Graphics.FromImage(newBMP);
                //Set the properties for the new graphic file
                oGraphics.SmoothingMode = SmoothingMode.HighQuality;
                oGraphics.InterpolationMode = InterpolationMode.High;

                //Draw the new graphic based on the resized bitmap
                oGraphics.DrawImage(originalBMP, 0, 0, width, height);

                newBMP.Save(saveAs);

                //Once finished with the bitmap objects, we deallocate them.
                originalBMP.Dispose();
                newBMP.Dispose();
                oGraphics.Dispose();
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }
    }
}